package com.seven.springboot.util;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.seven.springboot.enums.ValidStatus;

/**
 * String操作工具类
 * @author yinbenyang
 * @date 2018年3月15日下午3:44:32
 */
public class StringUtils {
	

    /**
     * Checks if a String is empty ("") or null.
     * <p>
     * <pre>
     * StringUtils.isEmpty(null)      = true
     * StringUtils.isEmpty("")        = true
     * StringUtils.isEmpty(" ")       = false
     * StringUtils.isEmpty("bob")     = false
     * StringUtils.isEmpty("  bob  ") = false
     * </pre>
     *
     * @param str the string to check,may be null
     * @return <code>true</code> if the String is empty or null
     */
    public static boolean isEmpty(String str) {
        return str == null
                || str.length() == 0
                || str.equals("null")
                || str.equals("NULL")
                || str.equals("\"null\"")
                || str.equals("\"NULL\"")
                || str.equals("“null”")
                || str.equals("“NULL”")
                || "NaN".equals(str);
    }

    /**
     * Checks if a String is not empty ("") or null.
     * <p>
     * <pre>
     * StringUtils.isNotEmpty(null)      = false
     * StringUtils.isNotEmpty("")        = false
     * StringUtils.isNotEmpty(" ")       = true
     * StringUtils.isNotEmpty("bob")     = true
     * StringUtils.isNotEmpty("  bob  ") = true
     * </pre>
     *
     * @param str the String to check,may be null
     * @return <code>true</code> if the String is not empty or null.
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * <p>
     * Compares two Strings, returning <code>true</code> if they are equal.
     * </p>
     * <p>
     * <p>
     * <code>null</code>s are handled without exceptions. Two <code>null</code>
     * references are considered to be equal. The comparison is case sensitive.
     * </p>
     * <p>
     * <pre>
     * StringUtils.equals(null, null)   = true
     * StringUtils.equals(null, "abc")  = false
     * StringUtils.equals("abc", null)  = false
     * StringUtils.equals("abc", "abc") = true
     * StringUtils.equals("abc", "ABC") = false
     * </pre>
     *
     * @param str1 the first String, may be null
     * @param str2 the second String, may be null
     * @return <code>true</code> if the Strings are equal, case sensitive, or
     * both <code>null</code>
     * @see String#equals(Object)
     */
    public static boolean equals(String str1, String str2) {
        return str1 == null ? str2 == null : str1.equals(str2);
    }

    /**
     * <p>
     * Compares two Strings, returning <code>true</code> if they are equal
     * ignoring the case.
     * </p>
     * <p>
     * <p>
     * <code>null</code>s are handled without exceptions. Two <code>null</code>
     * references are considered equal. Comparison is case insensitive.
     * </p>
     * <p>
     * <pre>
     * StringUtils.equalsIgnoreCase(null, null)   = true
     * StringUtils.equalsIgnoreCase(null, "abc")  = false
     * StringUtils.equalsIgnoreCase("abc", null)  = false
     * StringUtils.equalsIgnoreCase("abc", "abc") = true
     * StringUtils.equalsIgnoreCase("abc", "ABC") = true
     * </pre>
     *
     * @param str1 the first String, may be null
     * @param str2 the second String, may be null
     * @return <code>true</code> if the Strings are equal, case insensitive, or
     * both <code>null</code>
     * @see String#equalsIgnoreCase(String)
     */
    public static boolean equalsIgnoreCase(String str1, String str2) {
        return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
    }

    /**
     * <p>
     * Counts the length of String.
     * </p>
     * <p>
     * <pre>
     * StringUtils.count(null)			= 0
     * StringUtils.count("")			= 0
     * StringUtils.count("a*")			= 2
     * StringUtils.count("大小small")	= 9
     * </pre>
     *
     * @param str the String to check,may be null
     * @return the number of String.
     */
    public static int count(String str) {
        int length = 0;
        str = str.trim();
        if (isEmpty(str)) {
            return length;
        }
        char[] temp = str.toCharArray();
        for (char t : temp) {
            if (String.valueOf(t).matches("^[\\u4e00-\\u9fa5]*$")) {
                length += 2;
            } else if (String.valueOf(t).matches("^\\S*$")) {
                length += 1;
            }
        }
        return length;
    }

    /**
     * 将一个网页编码转化为unicode符号，比如"&#8212;转为—
     *
     * @param dataStr
     * @return
     */
    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            int system = 10;// 进制
            if (start == 0) {
                int t = dataStr.indexOf("&#");
                if (t < 0) {
                    return dataStr;
                }
                buffer.append(dataStr.subSequence(0, t));
                if (start != t)
                    start = t;
            }
            end = dataStr.indexOf(";", start + 2);
            String charStr = "";
            if (end != -1) {
                charStr = dataStr.substring(start + 2, end);

                // 判断进制
                char s = charStr.charAt(0);
                if (s == 'x' || s == 'X') {
                    system = 16;
                    charStr = charStr.substring(1);
                }
            }
            // 转换
            try {
                char letter = (char) Integer.parseInt(charStr, system);
                buffer.append(new Character(letter).toString());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            // 处理当前unicode字符到下一个unicode字符之间的非unicode字符
            start = dataStr.indexOf("&#", end);
            if (start - end > 1) {
                buffer.append(dataStr.substring(end + 1, start));
            }

            // 处理最后面的非unicode字符
            if (start == -1) {
                int length = dataStr.length();
                if (end + 1 != length) {
                    buffer.append(dataStr.substring(end + 1, length));
                }
            }
        }
        return buffer.toString();
    }

    /**
     * 随机获取一个字符串
     *
     * @param length : 获取的字符串长度
     * @return
     */
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyzAC0123456789";

        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }

        return sb.toString();
    }

    /**
     * 将字符串为： NUll 或者 无值的转换为空值""
     *
     * @param sourceStr
     * @return
     */
    public static String formatNull(String sourceStr) {

        if (isEmpty(sourceStr)) {
            return "";
        }

        return sourceStr;
    }

    /**
     * 判断字符串中是否存在中文字符
     *
     * @param str
     * @return
     */
    public static boolean isChineseChar(String str) {

        boolean temp = false;

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");

        Matcher m = p.matcher(str);

        if (m.find()) {

            temp = true;
        }

        return temp;
    }

    /**
     * Trim <i>all</i> whitespace from the given String:
     * leading, trailing, and in between characters.
     *
     * @param str the String to check
     * @return the trimmed String
     * @see Character#isWhitespace
     */
    public static String trimAllWhitespace(String str) {
        if (!(str != null && str.length() > 0)) {
            return str;
        }
        StringBuilder sb = new StringBuilder(str);
        int index = 0;
        while (sb.length() > index) {
            if (Character.isWhitespace(sb.charAt(index))) {
                sb.deleteCharAt(index);
            } else {
                index++;
            }
        }
        return sb.toString();
    }

    /**
     * 去空格，增加非空判断
     *
     * @param str
     * @return
     */
    public static String trim(String str) {
        if (str == null) {
            return str;
        }
        return str.trim();
    }

    /**
     * 是否含有屏蔽字符
     *
     * @param str
     * @return
     */
    public static boolean hasExcludeChar(String str) {
        if (str != null) {
            char[] chs = str.toCharArray();
            for (int i = 0; i < chs.length; i++) {

                if (Character.getType(chs[i]) == Character.PRIVATE_USE) {

                    return true;
                }

            }
        }
        return false;
    }

    /**
     * 检查指定的字符串中是有效的Mysql支持的UTF-8编码,该检测直接比较每个code point是否在0X0000~0XFFFF中(Mysql
     * utf8能够有效支持的UNICODE编码范围0X000~0XFFFF)
     *
     * @param str
     * @return
     */
    public static boolean isValidMySqlUTF8Fast(String str) {
        final int length = str.length();
        for (int i = 0; i < length; i++) {
            int c = str.codePointAt(i);
            if (c < 0X0000 || c > 0Xffff) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断字符是否是字母(包括大小写)或者数字
     *
     * @param cha
     * @return
     */
    public static boolean isLetterOrDigit(String cha) {
        String reg = "[\\w]+";
        Pattern pat = Pattern.compile(reg);
        Matcher mat = pat.matcher(cha);
        boolean result = mat.matches();
        return result;
    }

    /**
     * 判断字符是否是字母(包括大小写)或者数字
     *
     * @param cha
     * @return
     */
    public static boolean isLetterOrDigit(char cha) {
        return isLetterOrDigit("" + cha);
    }

    /**
     * Convenience method to return a Collection as a delimited (e.g. CSV)
     * String. E.g. useful for {@code toString()} implementations.
     *
     * @param coll  the Collection to display
     * @param delim the delimiter to use (probably a ",")
     * @return the delimited String
     */
    public static String collectionToDelimitedString(Collection<?> coll, String delim) {
        return collectionToDelimitedString(coll, delim, "", "");
    }

    /**
     * Convenience method to return a Collection as a delimited (e.g. CSV)
     * String. E.g. useful for {@code toString()} implementations.
     *
     * @param coll   the Collection to display
     * @param delim  the delimiter to use (probably a ",")
     * @param prefix the String to start each element with
     * @param suffix the String to end each element with
     * @return the delimited String
     */
    public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) {
        if (coll == null || coll.isEmpty()) {
            return "";
        }


        StringBuilder sb = new StringBuilder();
        Iterator<?> it = coll.iterator();
        while (it.hasNext()) {
            sb.append(prefix).append(it.next()).append(suffix);
            if (it.hasNext()) {
                sb.append(delim);
            }
        }
        return sb.toString();
    }

    /**
     * 将List转为以，分割的字符串
     *
     * @param stringList
     * @return
     */
    public static String listToString(List<String> stringList) {
        if (stringList == null) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        boolean flag = false;
        for (String string : stringList) {
            if (flag) {
                result.append(",");
            } else {
                flag = true;
            }
            result.append(string);
        }
        return result.toString();
    }
    
    /**
     * 将以,分割的字符串转为List
     *
     * @param str
     * @return
     */
    public static List<Integer> stringToList(String str, String character){
    	if (isEmpty(str)) {
            return null;
        }
    	String[] strs = str.split(character);
    	List<Integer> results = new ArrayList<>(strs.length);
    	for (String _str : strs) {
    		Integer result = Integer.parseInt(_str);
			if(!results.contains(result)){
				results.add(result);
			}
		}
    	return results;
    }
    
    public static Boolean parseValid(String value) throws Exception{
    	if(value == null){
    		throw new Exception("config value conot be null");
    	}
    	return (String.valueOf(ValidStatus.VALID.getIndex()).equals(value.trim()) || "true".equals(value.trim().toLowerCase()));
    }
    

    /**
     * 过滤HTML标签.
     * @param htmlContent - 网页内容
     * @return
     */
    public static String html2Text(String htmlContent) {
    	
    	//非空判断
    	if (isEmpty(htmlContent)) {
    		return null;
    	}
    	Pattern p_script, p_style, p_html; //定义规则
    	Matcher m_script, m_style, m_html; //匹配规则
    	//定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
    	String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; 

    	//定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
    	String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; 

    	//定义HTML标签的正则表达式
    	String regEx_html = "<[^>]+>";
    	
    	//过滤script标签
    	p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
    	m_script = p_script.matcher(htmlContent);
    	htmlContent = m_script.replaceAll(""); 

    	//过滤style标签
    	p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
    	m_style = p_style.matcher(htmlContent);
    	htmlContent = m_style.replaceAll(""); 

    	//过滤html标签
    	p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
    	m_html = p_html.matcher(htmlContent);
    	htmlContent = m_html.replaceAll(""); 
    	
    	//过滤空格
    	htmlContent = htmlContent.replaceAll("&nbsp;", "");
    	return htmlContent;
    }
    /**
     * 字符串加星号掩码
     * @author jiliangshan
     * @date 2017-2-9 下午6:37:56
     */
    public static String transfer(String prior, String transferChar, int from, int transferLen) {
		if(isEmpty(prior)) {
			return prior;
		}
		int len = prior.length();
		if(len <= from || from < 0) {
			return prior;
		}
		
		String prefix = prior.substring(0, from);
		String remain = prior.substring(from);
		if(remain == null) {
			return prior;
		}
		int remainLen = remain.length();
		if(transferLen > 0) {
			StringBuffer transBuf = new StringBuffer();
			if(remainLen >= transferLen) {
				for (int i = 0; i < transferLen; i++) {
					transBuf.append(transferChar);
				}
				String suffix = prior.substring(from + transferLen);
				return prefix + transBuf.toString() + suffix;
			} else {
				for (int i = 0; i < remainLen; i++) {
					transBuf.append(transferChar);
				}
				return prefix + transBuf.toString();
			}
		}
		return prior;
		
	}

    /**
     * 字符串转换unicode
     */
    public static String string2Unicode(String string) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            // 取出每一个字符
            char c = string.charAt(i);
            // 转换为unicode
            unicode.append("\\u" + Integer.toHexString(c));
        }
        return unicode.toString();
    }

    /**
     * unicode 转字符串
     *
     * @param unicode
     * @return
     */
    public static String unicode2String(String unicode) {

        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);
            // 追加成string
            string.append((char) data);
        }
        return string.toString();
    }
   
    /**
     * 翻转字符串，支持中文
     * 
     * @param str
     * @return
     */
	public static String reverse(String str) {
		if (str == null)
			return null;
		char[] cs = str.toCharArray();
		int len = cs.length;
		int i = 0;
		while (i < len - i - 1) {
			cs[i] = (char) (cs[i] ^ cs[len - i - 1]);
			cs[len - i - 1] = (char) (cs[i] ^ cs[len - i - 1]);
			cs[i] = (char) (cs[i] ^ cs[len - i - 1]);
			i++;
		}
		return new String(cs);
	}
    
	/**
	 * 半角转全角
	 * 
	 * @param input
	 *            String.
	 * @return 全角字符串.
	 */
	public static String toSBC(String input) {
		char c[] = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == ' ') {
				c[i] = '\u3000';
			} else if (c[i] < '\177') {
				c[i] = (char) (c[i] + 65248);

			}
		}
		return new String(c);
	}
    
	/**
	 * 全角转半角
	 * 
	 * @param input
	 *            String.
	 * @return 半角字符串
	 */
	public static String toDBC(String input) {

		char c[] = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == '\u3000') {
				c[i] = ' ';
			} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
				c[i] = (char) (c[i] - 65248);

			}
		}
		String returnString = new String(c);

		return returnString;
	}
	
	/**
	 * 把字符串最后一个，去掉
	 * 
	 * @param str
	 * @return
	 */
	public static String subLastComma(String str) {

		if (isNotEmpty(str)) {
			char lastCarc = str.charAt(str.length() - 1);
			String last = Character.toString(lastCarc);
			if (last.equals(",") || last.equals("，")) {
				str = str.substring(0, str.length() - 1);
			}
		}

		return str;
	}
	
	public static void main(String[] args) {
		String dbc = subLastComma("12345,,，");
		System.out.println(dbc);
	}
}
